# -*- coding: utf-8 -*-
# @Date   : 2021/07/15
# @File   : R75_PastYearARAndARRatioCheck_CF.py
# @Author : zhanghengfeng

'''eof
name:申请企业上一年货物贸易回款值及收汇率校验
code:R75_PastYearARAndARRatioCheck_CF
tableName:
columnName:
groups:出口信息模块
dependencies:CF_CQ_DSJ
type:常用指标
dataSourceType:
eof'''

import pandas as pd
import datetime

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

def isfloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x)>=0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False

def goodslist_method(data,length):
    '''
    Explanation
    --------------
    获取近期指定月份数长度升序排列的出口货物金额列表
    
    Parameters
    ------------
    data: json
        数据接口直接获取到的数据
    
    length: int
        时间月份数长度
        
    Return
    ------
    amount_list: list or str即u'缺失值'
        金额列表
    '''
    #获取receipt表失败时，返回缺失值
    try:
        receipt = data['body']['baseInfo'][0]['receipt']
        if receipt in null_type_list:
            return u'缺失值'
        elif receipt == []:
            return 0
        elif isinstance(receipt,list) and len(receipt)>0:
        #    #获取receipt中最大申报月份数
        #    timelist = []   
        #    for i in data['detail']['baseInfo']['receipt']:
        #        timelist.append(int(i["month"]))
        ##    np.max(timelist)
            
            #生成字符串形式的升序时间列表
            last_month_list = [(datetime.datetime(datetime.datetime.now().year,1,1) - pd.tseries.offsets.DateOffset\
                                (months=i)).strftime('%Y%m%d')[:6] for i in range(1, 1+length)]
            #根据上述列表生成对应月份为0元的记录的字典
            last_month_dict = {}
            for i in last_month_list:
                last_month_dict[i] = 0
            #遍历所有的申报记录，对相应月份进行字段值更新
            errorConts = 0
            for i in receipt:
                try:
                    #月份
                    month = i.get('month')
                    #金额
                    goods = i.get('goods')
                    if isfloat(month) and isfloat(goods) and isinstance(int(month),int) and len(month) == 6:
                        if i['month'] in last_month_list and float(goods) > 0:
                            last_month_dict.update({i['month']:float(i['goods'])})
                        else:
                            pass
                    else:
                        errorConts += 1
                except:
                    errorConts += 1
            if errorConts == len(receipt):
                return u'缺失值' 
            else:
                #返回列表形式的字典字段值
                amount_list = list(last_month_dict.values())          
                return amount_list
        else:
            return u'缺失值' 
    except:
        return u'缺失值' 

def R75_PastYearARAndARRatioCheck_CF():
    list_result = goodslist_method(CF_CQ_DSJ,12) 
    if list_result == u'缺失值':
        return u'缺失值'
    else:
        amount = sum(list_result)
        try:
            exchangeRate = CF_CQ_DSJ['body']['baseInfo'][0]['exchangeRate']
            ratio = 0
            if exchangeRate in null_type_list:
                return u'缺失值'
            elif exchangeRate == []:
                return 0
            elif isinstance(exchangeRate,list) and len(exchangeRate)>0:
                #遍历所有的申报记录，对相应月份进行字段值更新 
                errorConts = 0
                missConts = 0
                for i in exchangeRate:
                    try:
                        #收汇率
                        collectRate = i.get('collectRate')
                        #收汇年份
                        year = i.get('year')
                        #上一年度年份，int
                        lastYear = datetime.datetime.now().year - 1
                        if isfloat(collectRate) and isfloat(year) and isinstance(int(year),int) and len(year) == 4:
                            if year in [lastYear,str(lastYear)]:
                                ratio += float(collectRate)
                                break
                            else:
                                missConts += 1
                        else:
                            errorConts += 1
                    except:
                        errorConts += 1
            else:
                return u'缺失值'
            if missConts + errorConts == len(exchangeRate):
                return u'缺失值'
            else:
                if amount > 500000 and ratio > 0.8:
                    return 1
                else:
                    return 0
        except:
            return u'缺失值'
result = R75_PastYearARAndARRatioCheck_CF()
    